import { ref, onMounted, watch } from "vue";

export function usePagination(
  apiEndpoint: Function,
  options: {
    pageSize?: Number;
    searchParams?: Object;
    dealList: Function;
  } = {
    dealList: (list: any) => list,
  }
) {
  const currentPage = ref(1);
  const totalItems = ref(0);
  const list = ref([]);

  // 异步获取数据的函数
  const fetchData = async () => {
    try {
      const response = await apiEndpoint({
        page: currentPage.value,
        size: options.pageSize || 10,
        ...(options.searchParams || {}),
      });
    //   const data = await response.json();
      list.value = options.dealList(response.list) ;
      totalItems.value = response.total;
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  // 监听 currentPage 的变化，当改变时重新获取数据
//   watch(currentPage, fetchData);
  const pageChange = (page:number) => {
     currentPage.value = page
     fetchData()
  }

  // 返回所有必要的状态和函数
  return {
    currentPage,
    totalItems,
    list,
    fetchData,
    pageChange
  };
}
